import { sessionStorage } from '@/utils/storage'
import { formatDate } from '@/utils/time'

export default function projectsData({ isPc, formData, paginationQuery, apiList, initAos, handleToContractDetails, total, pageType, inletPage }) {
    const formRef = ref()
    const loading = ref(false)
    const tableData = ref([])
    const tabData = ref([
        { title: '总包立项', code: '0' },
        { title: '内部委托', code: '1' }
    ])
    const selectedrowData = ref({
        projectId: '0'
    })

    onMounted(() => {
        if (pageType == 'childrenPage') {
            sessionStorage.set('contractSessionData', {})
        }
        initAos()
        getList()
    })

    async function getList(type) {
        const params = {
            ...formData,
            ...paginationQuery
        }
        const res = await apiList(params)
        const newData = res.data.map(item => {
            return {
                ...item,
                sqrq: formatDate(item.sqrq || item.contractInitiationSqrq).fmt15
            }
        })

        if (isPc) {
            tableData.value = newData
        } else {
            if (type == 'touchEnd') {
                tableData.value = []
            }
            if (res) {
                tableData.value.push(...newData)
            }
        }
        total.value = res.total
    }

    function setRowClass({ row }) {
        if (inletPage == 0) {
            if (selectedrowData.value.projectId == row.projectId) {
                return 'table-row selected-row-color'
            }
        }
        if (inletPage == 1) {
            if (selectedrowData.value.gllxid == row.gllxid) {
                return 'table-row selected-row-color'
            }
        }
        return 'table-row'
    }

    const handleChangeTab = tab => {
        tableData.value = []
        formData.conditions.lxyt = tab.paneName
        getList()
    }

    function handleSelectionChange(row) {
        if (row) {
            selectedrowData.value = row
            let data = {}
            if (pageType == 'inletPage') {
                data = row
            } else {
                const { uuid, lxyt, gcbh, gcmc } = row
                data = {
                    contractInitiationUuId: uuid,
                    projectName: gcmc,
                    projectId: gcbh,
                    lxyt
                }
            }
            data.gllxid = row.gllxid || ''
            handleToContractDetails(data)
        }
    }

    return {
        formRef,
        loading,
        selectedrowData,
        tabData,
        tableData,
        getList,
        setRowClass,
        handleChangeTab,
        handleSelectionChange
    }
}
